//
//  WJNetTool.m
//  WJBSApp
//
//  Created by dllo on 16/7/13.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJNetTool.h"

@implementation WJNetTool

+ (AFHTTPSessionManager *)shareAFManager {
    static AFHTTPSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        // HTTPS
        manager.securityPolicy.allowInvalidCertificates = YES;
        // 4.设置响应数据类型
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    });
    return manager;
}


+ (void)GET:(NSString *)url body:(id)body header:(NSDictionary *)header response:(WJResponseStyle)responseStyle success:(successBlock)success failure:(failureBlock)failure {
    
    AFHTTPSessionManager *manager = [WJNetTool shareAFManager];
    
    // 2.设置请求头
    if (header) {
        for (NSString *key in header) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    
    // 3.返回值类型
    switch (responseStyle) {
        case WJJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WJDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case WJXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    

    // 5. UTF8转码   将url转码为utf-8
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 6.使用AFN进行网络请求
    [manager GET:url parameters:body headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject && [responseObject isKindOfClass:[NSDictionary class]] && success) {
            success(responseObject);
        } else {
            if (failure) failure(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) failure(error);
    }];
}


+ (void)POST:(NSString *)url body:(id)body bodyStyle:(WJBodyStyle)bodyStyle header:(NSDictionary *)header response:(WJResponseStyle)responseStyle success:(successBlock)success failure:(failureBlock)failure {
    
    AFHTTPSessionManager *manager = [WJNetTool shareAFManager];

    // 1.设置请求头
    if (header) {
        for (NSString *key in header) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    
    // 2.设置Body的数据类型
    switch (bodyStyle) {
        case WJBodyJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case WJBodyString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                return parameters;
            }];
            break;
        default:
            break;
    }
    
    
    // 3.返回值类型
    switch (responseStyle) {
        case WJJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WJDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case WJXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    
    // 4. UTF8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 5.使用AFN进行网络请求
    [manager POST:url parameters:body headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject && success) {
            success(responseObject);
        } else {
            if (failure) failure(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) failure(nil);
    }];  
}

///> 批量上传图片
- (void)startMultiPartUploadTaskWithURL:(NSString *)url imagesArray:(NSArray *)images parameterOfimages:(NSString *)parameter parametersDict:(NSDictionary *)parameters succeedBlock:(void (^)(NSDictionary *dict))succeedBlock failedBlock:(void (^)(NSError *error))failedBlock {
    
    for (int i = 0; i < images.count; i++) {
        if (![images[i] isKindOfClass:[UIImage class]]) {
            NSLog(@"images中第%d个元素不是UIImage对象",i+1);
        }
    }
    
    AFHTTPSessionManager *manager = [WJNetTool shareAFManager];
    
    [manager POST:url parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        ///> 如果有多个文件，就重复设置文件部分，使用不同的`name`标识
        for (NSInteger i = 0; i < images.count; i++) {
            UIImage *image = images[i];
            NSData *imageData = [self compressOriginalImage:image toMaxDataSizeKBytes:100];
            NSString *imageType = [self typeForImageData:imageData];
            NSString *fileName = [NSString stringWithFormat:@"%tu.%@",i,imageType];
            NSString *fileType = [NSString stringWithFormat:@"image/%@",imageType];
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:fileType];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if (succeedBlock) succeedBlock(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
         if (failedBlock) failedBlock(error);
        }
    }];
}

- (NSString *)typeForImageData:(NSData *)data {
    uint8_t c;
    
    [data getBytes:&c length:1];
    
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
            
        case 0x4D:
            return @"tiff";
            
    }
    return nil;
}

#pragma mark - 压缩图片
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size {
    UIImage *OriginalImage = image;
    
    // 执行这句代码之后会有一个范围 例如500m 会是 100m～500k
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    
    // 执行while循环 如果第一次压缩不会小雨100k 那么减小尺寸在重新开始压缩
    while (dataKBytes > size)
    {
        while (dataKBytes > size && maxQuality > 0.1f)
        {
            maxQuality = maxQuality - 0.1f;
            data = UIImageJPEGRepresentation(image, maxQuality);
            dataKBytes = data.length / 1000.0;
            if(dataKBytes <= size )
            {
                return data;
            }
        }
        OriginalImage =[self compressOriginalImage:OriginalImage toWidth:OriginalImage.size.width * 0.8];
        image = OriginalImage;
        data = UIImageJPEGRepresentation(image, 1.0);
        dataKBytes = data.length / 1000.0;
        maxQuality = 0.9f;
    }
    return data;
}

#pragma mark - 改变图片的大小
- (UIImage *)compressOriginalImage:(UIImage *)image toWidth:(CGFloat)targetWidth {
    CGSize imageSize = image.size;
    CGFloat Originalwidth = imageSize.width;
    CGFloat Originalheight = imageSize.height;
    CGFloat targetHeight = Originalheight / Originalwidth * targetWidth;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [image drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}



///> 下载文件
+ (void)downloadFileWithFileUrl:(NSString *)requestURL progress:(void (^)(NSString * name,float progress))progress downloadFailure:(void (^)(NSError *error))failure {
    
    //创建传话管理者
    AFHTTPSessionManager *manager = [WJNetTool shareAFManager];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",@"",requestURL]]];
    //下载文件
    /*
     第一个参数:请求对象
     第二个参数:progress 进度回调
     第三个参数:destination 回调(目标位置)
     有返回值
     targetPath:临时文件路径
     response:响应头信息
     第四个参数:completionHandler 下载完成后的回调
     filePath:最终的文件路径
     */
    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request
                                          progress:^(NSProgress * _Nonnull downloadProgress)
                                          {
                                              progress(requestURL,1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
                                          }
                                         destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response)
                                          {
                                              //保存的文件路径
                                              NSString *fullPath = [NSString stringWithFormat:@"%@/%@", @"", requestURL];
                                              NSLog(@"保存的文件路径----%@",fullPath);
                                              return [NSURL fileURLWithPath:fullPath];
                                          }
                                          completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error)
                                          {
                                              if (failure) failure(error);
                                          }];
    
    
    //执行Task
    [download resume];
}

+ (void)cancelRequest {
    if ([[WJNetTool shareAFManager].tasks count] > 0) {
        [[WJNetTool shareAFManager].tasks makeObjectsPerformSelector:@selector(cancel)];
    }
}
@end
